package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constant.WmNewsMessageConstants;
import com.heima.common.test4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async //标明该方法为异步方法
    @Transactional
    public void autoScanWmNews(Integer id) {
        //1.查询自媒体文章
        try {
            //异步可能出现读不到数据的情况
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        WmNews wmNews = wmNewsMapper.selectById(id);
        log.info("【获取自媒体文章】:{}",wmNews);
        //从文章中提取文章和图片
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            Map<String,Object> resultMap = compileContentsAndImages(wmNews);
            //2.审核文本内容
            log.info("【审核文本内容】");
            boolean isTextScan = handleTextScan( (String)resultMap.get("text"),wmNews);
            //boolean isTextScan = true;
            if(!isTextScan)return;
            //3.审核图片内容
            log.info("【审核图片内容】");
            //boolean isImageScan =  handleImageScan((List<String>) resultMap.get("images"),wmNews);
            boolean isImageScan = true;
            if(!isImageScan)return;
            //自管理敏感词过滤
            boolean isSensitive = handleSensitiveScan((String)resultMap.get("text"),wmNews);
            if(!isSensitive)return;
        }else if(wmNews.getStatus().equals(WmNews.Status.FAIL.getCode())){
            return;
        }else if(!wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())){
            return;
        }
        //4.审核成功，保存app端相关文章数据
        log.info("【审核成功，保存app端相关文章数据】");
        ResponseResult responseResult = saveAppArticle(wmNews);
        if(!responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }
        //回填article_id
        wmNews.setArticleId((Long) responseResult.getData());
        log.info("【回填article_id】:{}",responseResult.getData());
        updateWmNews(wmNews,(short) 9,"审核成功");


    }

    /**
     * 自管理铭感词审核
     * @param text
     * @return
     */
    private boolean handleSensitiveScan(String text,WmNews wmNews) {
        log.info("【自管理敏感词审核】");
        boolean flag = true;
        //获取所有铭感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        //初始化敏感词库
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveList);
        //查看文中是否包含铭感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (map.size() > 0) {
            updateWmNews(wmNews,(short)2,"当前文章存在违规内容");
            flag = false;
            return flag;
        }
        return flag;
    }

    /**
     * 保存app端相关文章数据
     * @param wmNews
     */
    @Transactional
    public ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        return responseResult;
    }


    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if(images == null || images.size() == 0){
            return flag;
        }

        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        try{
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片识别 byte[] -> bufferImage
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                BufferedImage read = ImageIO.read(bais);
                log.info("【图片识别】:{}",read);
                String result = tess4jClient.doOCR(read);
                log.info("【识别文字】:{}",result
                );
                //过滤文字
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }
                imageList.add(bytes);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //aliyun审核图片
        //pass
//        try {
//            Map map = greenImageScan.imageScan(imageList);
//            if(map != null){
//                //审核失败
//                if(map.get("suggestion").equals("block")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
//                }
//
//                //不确定信息  需要人工审核
//                if(map.get("suggestion").equals("review")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
//                }
//            }
//
//        } catch (Exception e) {
//            flag = false;
//            e.printStackTrace();
//        }
        return true;
    }


    /**
     * 审核纯文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
//        boolean flag = true;
//        if((wmNews.getTitle()+"-"+content).length() == 0){
//            return flag;
//        }
//        try {
//            Map map = greenTextScan.greeTextScan((wmNews.getTitle()+"-"+content));
//            if(map != null){
//                //审核失败
//                if(map.get("suggestion").equals("block")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
//                }
//
//                //不确定信息  需要人工审核
//                if(map.get("suggestion").equals("review")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
//                }
//            }
//        } catch (Exception e) {
//            flag = false;
//            e.printStackTrace();
//        }

        updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
        if((wmNews.getTitle()+"-"+content).length() == 0){
            return true;
        }
        //修改审核
        log.info("【总是需要人工审核】");
        return false;
        //审核总是成功
        //return true;

    }

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    @Transactional
    public void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 提取图片和文本内容
     * @param wmNews
     * @return
     */
    private Map<String, Object> compileContentsAndImages(WmNews wmNews) {
        //存储文本
        StringBuffer text = new StringBuffer();
        //存储图片
        List<String> images = new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        //从文章中提取文本和图片
        List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }else if(map.get("type").equals("text")){
                text.append((String) map.get("value"));
            }
        }

        resultMap.put("text",text.toString());
        //从封面中提取图片
        if(wmNews.getImages()!=null && !wmNews.getImages().isEmpty()){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        resultMap.put("images",images);

        return resultMap;
    }
}
